<?php
class Db_Products_CategoryOffers extends Common {
    protected static $tableName = TAB_CATEGORY_OFFERS;
    protected static $dbFields = array(
		'id',
        'co_parent_category_id',
        'co_connected_category_id',
        'co_is_persistent',
		'co_position'
	);

    /**
     * @var Db_Products_Category_Offers
    */
	public static $positionField = 'co_position';

    public $objectArray;

	public $id;
    public $co_parent_category_id;
    public $co_connected_category_id;
    public $co_is_persistent;
    public $co_position;

    function __construct($value=NULL, $fieldName=NULL) {
        parent::__construct($value, $fieldName);
    }


	/**
	 * @static
	 * @param $categoryId
	 * @return bool|mixed
	 */
	public static function getOffersByCategoryId($categoryId) {
		if (!$categoryId) {
			return false;
		}
		$sql = "SELECT `co`.*, `cat_parent`.`pc_name` AS `parent_category_name`,  `cat_connected`.`pc_name` AS `connected_category_name` FROM ?f co
				LEFT JOIN ?f cat_parent ON `cat_parent`.`id` = `co`.`co_parent_category_id` AND `cat_parent`.`deleted` = 0
				LEFT JOIN ?f cat_connected ON `cat_connected`.`id` = `co`.`co_connected_category_id` AND `cat_connected`.`deleted` = 0
				WHERE `co_parent_category_id` = ? ORDER BY `co`.`co_position` ASC";
		return self::$DB->select($sql,self::$tableName, TAB_CATEGORIES, TAB_CATEGORIES, $categoryId);

	}
	public static function deleteCategoryOffer($categoryOfferId) {
		if (!$categoryOfferId) {
			return false;
		}
		$sql = "DELETE FROM ?f WHERE `id` = ? ";
		self::$DB->q($sql,self::$tableName, $categoryOfferId);
	}

	public static function maxPositionOffersByParentCategoryId($categoryId) {
		if (!$categoryId) {
			return false;
		}
		$sql = "SELECT MAX(co_position) FROM ?f WHERE `co_parent_category_id` = ? ";
		return self::$DB->selectCell($sql,self::$tableName, $categoryId);
	}

	public static function getPersistentCategoryIdByParentCategoryId($categoryId) {
		if (!$categoryId) {
			return false;
		}
		$sql = "SELECT `co_connected_category_id` FROM ?f WHERE `co_parent_category_id` = ? AND `co_is_persistent` = 1";
		return self::$DB->selectCell($sql,self::$tableName, $categoryId);
	}

	public static function getConnectedCategoryIdByParentCategoryId($parentCategoriesId) {
		if (!$parentCategoriesId) {
			return false;
		}
		$sql = "SELECT `co_connected_category_id`, `co_position` FROM ?f WHERE `co_parent_category_id` IN ( ? ) AND `co_is_persistent` = 0 ORDER BY `co_position` ASC";
		$result = self::$DB->select($sql,self::$tableName, $parentCategoriesId);
        $returnData = array();
		if ($result) {
			foreach ($result as $categoryId) {
				if (!in_array($categoryId, $parentCategoriesId)) {
					$returnData[] = $categoryId["co_connected_category_id"];
				}
			}
		}
		return $returnData;
	}
}